package flows

import (
	"encoding/json"
	"strconv"
	"time"
	"zimuzu_cvn_web_api/model"
	"zimuzu_cvn_web_api/pkg/drive/redis"
	"zimuzu_cvn_web_api/pkg/e"
)

type ProfitDetailMoreResponse struct {
	Date   string           `json:"date"`
	List   []DetailMoreList `json:"list"`
	Detail []ProfitDetailMoreData
	Page   model.PageList
}
type DetailMoreList struct {
	Source int     `json:"source"`
	Profit float64 `json:"profit"`
}
type ProfitDetailMoreData struct {
	Time    string  `json:"time"`
	Date    string  `json:"date"`
	Flow    int64   `json:"flow"`
	NetFlow int64   `json:"net_flow"`
	Rate    float64 `json:"rate"`
	Cvn     float64 `json:"cvn"`
	NetCvn  float64 `json:"net_cvn"`
}

// 获取收益详情列表接口
func ProfitDetailRelation(Uid int64, page, per int) (res ProfitDetailMoreResponse, err error) {

	pageStr := strconv.Itoa(page) + "_" + strconv.Itoa(per)
	dateSettle := time.Now().AddDate(0, 0, -1).Format(e.TimeFormatD)
	cacheKey := "temp:profit:detail:relation:" + strconv.FormatInt(Uid, 10) + ":" + dateSettle + ":" + pageStr
	if redis.Exists(cacheKey) {
		rS, err := redis.Get(cacheKey)
		if err != nil {
			return res, err
		}
		err = json.Unmarshal([]byte(rS), &res)
		if err != nil {
			return res, err
		}
		return res, nil
	}

	// 获取昨日时间
	res.Date = dateSettle

	// 获取每条线路的流量和收益
	profitData, err := GetNetSourceNetData(dateSettle)
	if err != nil {
		return res, err
	}
	var tempData DetailMoreList
	for _, k := range profitData {
		tempData.Source = k.Source
		tempData.Profit = e.Decimal(k.Cvn, 2)
		res.List = append(res.List, tempData)
	}

	// 获取用户最近结算数据
	profitListDbs, err := model.GetUserProfitListFromDB(Uid, page, per)
	if err != nil {
		return res, err
	}
	res.Page.CountItem, err = model.GetUserProfitListCountDB(Uid)
	if err != nil {
		return res, err
	}
	res.Page.CountPage = e.ListPage(res.Page.CountItem, per)
	var tempDetail ProfitDetailMoreData
	for _, kkk := range profitListDbs {
		tempDetail.Date = kkk.Date
		tempDetail.Time = time.Unix(e.StrToTime(kkk.Date+" 00:00:00"), 0).Format("01/02")
		tempDetail.Cvn = e.Decimal(kkk.Cvn, 2)
		tempDetail.Flow = kkk.Flows
		tempDetail.NetFlow = kkk.NetFlows
		tempDetail.NetCvn = e.Decimal(kkk.NetCvn, 2)
		tempDetail.Rate = kkk.Rate
		res.Detail = append(res.Detail, tempDetail)
	}

	// 写入缓存数据，缓存一天
	rB, err := json.Marshal(res)
	if err != nil {
		return res, err
	}
	redis.SetUnRe(cacheKey, string(rB), e.TimeFormatMin*3)
	return res, nil
}

// 获取每条线路的总收益
func GetNetSourceNetData(Date string) (res []model.ProfitTotalDB, err error) {

	if Date == "" {
		Date = time.Now().AddDate(0, 0, -1).Format(e.TimeFormatD)
	}
	cacheKey := "temp:net:source:date:" + Date
	if redis.Exists(cacheKey) {
		rD, err := redis.Get(cacheKey)
		if err != nil {
			e.Log("info", "NetSource error 1")
			redis.UnDelete(cacheKey)
			return res, err
		}
		err = json.Unmarshal([]byte(rD), &res)
		if err != nil {
			e.Log("info", "NetSource error 2")
			redis.UnDelete(cacheKey)
			return res, err
		}
		if res == nil {
			e.Log("info", "NetSource error 3")
			redis.UnDelete(cacheKey)
		} else {
			return res, nil
		}
	}

	// 从数据库取值
	res, err = model.GetNetProfitList(Date)
	if err != nil {
		e.Log("info", "NetSource error 4")
		// 如果数据库没有写入，则调用写入接口写入数据
		_, err = GetTheDateCdnProfit(Date)
		res, err = model.GetNetProfitList(Date)
		if err != nil {
			e.Log("info", "NetSource error 6")
			return res, err
		}
	}

	// 写入缓存数据
	rB, err := json.Marshal(res)
	if err != nil {
		e.Log("info", "NetSource error 7")
		return res, err
	}
	redis.SetUnRe(cacheKey, string(rB), e.TimeFormatHour)
	return res, nil
}

// 获取收益详情指定日期结算数据
func TheDataProfitDetailRelation(Uid int64, Source int, Date string, Page, Per int) (res []model.MultipleNodePaymentResponse, err error) {
	pageStr := strconv.Itoa(Page) + "_" + strconv.Itoa(Per)
	cacheKey := "temp:profit:detail:the:date:" + strconv.FormatInt(Uid, 10) + ":" + Date + ":" + pageStr
	if redis.Exists(cacheKey) {
		e.Log("err", "缓存存在，直接读取缓存数据")
		rS, err := redis.Get(cacheKey)
		if err != nil {
			e.Log("err", "读取缓存数据异常，清除缓存")
			redis.UnDelete(cacheKey)
			return res, err
		}
		err = json.Unmarshal([]byte(rS), &res)
		if err != nil {
			e.Log("err", "读取缓存数据异常2，清除缓存")
			redis.UnDelete(cacheKey)
			return res, err
		}
		if res == nil {
			e.Log("err", "读取缓存数据异常3，清除缓存")
			redis.UnDelete(cacheKey)
		} else {
			return res, nil
		}
	}

	// 直接获取数据库
	// 需要做处理
	resTemp, err := model.GetUserTheDateNodePayment(Uid, Source, Date, Page, Per)
	if err != nil {
		e.Log("err", "直接获取数据库，err=", err.Error())
		return res, err
	}

	// 取指定日期是否已结算
	settleStatus, err := model.GetUserPaymentByDate(Uid, Date)
	if err != nil {
		e.Log("err", "取指定日期是否已结算，err=", err.Error())
		return res, err
	}

	var temp model.MultipleNodePaymentResponse
	for _, k := range resTemp {
		temp.Name = k.Name
		temp.Up = k.Up
		temp.SourceFlows = k.SourceFlows
		temp.SourceRate = k.SourceRate
		temp.Cvn = k.Cvn
		temp.OnlineTime = k.OnlineTime
		temp.SettleStatus = k.Status
		if settleStatus == 3 {
			temp.Status = 1
		} else {
			temp.Status = 0
		}
		res = append(res, temp)
	}
	rD, err := json.Marshal(res)
	if err != nil {
		e.Log("err", "解析数据异常，err=", err.Error())
		return res, err
	}
	redis.SetUnRe(cacheKey, string(rD), e.TimeFormatMin*3)
	return res, nil
}
